const $ = require("jquery");
const _ = require("lodash");

module.exports = class Task {

    constructor(){
        this.init();
    }

    init() {
        this.taskItemClassList = ["list-group-item-warning","list-group-item-info"];
        this.storage = window.localStorage;
        this.taskList = JSON.parse(this.storage.getItem("taskList")) || [];
        if(this.taskList.length >= 0){
            this.renderTaskList();
        }
        this.bindAddTaskEvent();
    }

    bindAddTaskEvent() {
        $("#add-submit").on("click", e => {
            e.preventDefault();
            let newTask = $("#add-task-input").val();
            if (newTask == "") return;
            this.addTask(newTask);
            $("#add-task-input").val("");
        });
    }
    bindRemoveTaskEvent(){
        $(".remove").on("click", e => {
            e.preventDefault();
            let removeTaskContent = $(e.target).parent().children("span:first-child").text();
            this.removeTask(removeTaskContent);
        });
    }

    addTask(newTask) {
        this.taskList.push(newTask);
        this.refreshTaskList();
    }

    removeTask(removeTaskContent) {
        _.pull(this.taskList, removeTaskContent);
        this.refreshTaskList();
    }

    refreshTaskList() {
        this.storage.setItem("taskList",JSON.stringify(this.taskList));
        this.renderTaskList();
    }

    renderTaskList() {
        $(".task-list").html("");
        this.taskList.map((value, index) => {
            let tpl = this.renderTaskItem(value, index);
            $(".task-list").append(tpl);
        });
        this.bindRemoveTaskEvent();
    }

    renderTaskItem(value, index) {
        let showIndex = index % 2;
        let taskItemClass = this.taskItemClassList[showIndex];
        let tpl = `
        <div class="list-group-item ${taskItemClass}">
            <span>${value}</span>
            <button type="button" class="close remove" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        `;
        return tpl;
    }
}



